<template>
  <div>
    <el-row>
      <el-col :span="2">
        <el-button type="primary" @click="addItem"><el-icon :size="20"><CirclePlus /></el-icon>发布新菜品</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="getMenu"><el-icon :size="20"><Memo /></el-icon>管理菜单</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="warning" @click="getDishAnalysis">菜品数据分析</el-button>
      </el-col>
    </el-row>
    
    <el-row>
      <el-col :span="18">
        <el-table :data="menuItems" style="width: 100%" height="500">
          <el-table-column v-if="!analysisVisible" prop="dish_name" label="菜品名称" width="80"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="dish_category" label="分类" width="80"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="price" label="价格" width="80"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="description" label="描述" width="180"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="ingredient" label="成分" width="150"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="nutritionInfo" label="营养信息" width="180"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="allergen" label="过敏原" width="80"></el-table-column>
          <el-table-column v-if="!analysisVisible" prop="isSignatureDish" label="主打菜品" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.isSignatureDish ? 'success' : 'info'">
                {{ scope.row.isSignatureDish ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="!analysisVisible" label="操作" width="180">
            <template #default="scope">
              <el-button size="mini" type="primary" @click="editDish(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteDish(scope.row.dish_ID)"><el-icon ><Delete :size="20"/></el-icon></el-button>
            </template>
          </el-table-column>

          <el-table-column v-if="analysisVisible" prop="dish_name" label="菜品名称" width="120"></el-table-column>
          <el-table-column v-if="analysisVisible" prop="average_rating" label="评分" width="80" sortable></el-table-column>
          <el-table-column v-if="analysisVisible" prop="total_sales" label="销量" width="80" sortable></el-table-column>
          <el-table-column v-if="analysisVisible" prop="top_customer_ID" label="购买最多的人ID" width="180"></el-table-column>
          <el-table-column v-if="analysisVisible" prop="isSignatureDish" label="主打菜品" width="120"
            :filters="[
              { text: '是', value: '是' },
              { text: '否', value: '否' },
            ]"
            :filter-method="filterTag"
            filter-placement="bottom-end"
          >
            <template #default="scope">
              <el-tag :type="scope.row.isSignatureDish ? 'success' : 'info'">
                {{ scope.row.isSignatureDish ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="analysisVisible" label="操作" width="180">
            <template #default="scope">
              <el-button size="mini" type="primary" @click="editDish(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteDish(scope.row.dish_ID)"><el-icon ><Delete :size="20"/></el-icon></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col :span="4">
        <div v-if="formVisible">
          <el-form :model="currentDish" label-width="120px" class="narrow-form">
            <el-form-item label="菜品名称">
              <el-input v-model="currentDish.dish_name"></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="currentDish.dish_category" placeholder="请选择分类">
                <el-option label="菜品" value="菜品"></el-option>
                <el-option label="主食" value="主食"></el-option>
                <el-option label="饮品" value="饮品"></el-option>
                <el-option label="甜品" value="甜品"></el-option>
                <el-option label="小吃" value="小吃"></el-option>
                <el-option label="水果" value="水果"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="currentDish.price" type="number" step="0.01"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="currentDish.description"></el-input>
            </el-form-item>
            <el-form-item label="成分">
              <el-input v-model="currentDish.ingredient"></el-input>
            </el-form-item>
            <el-form-item label="营养信息">
              <el-input v-model="currentDish.nutritionInfo"></el-input>
            </el-form-item>
            <el-form-item label="过敏原">
              <el-input v-model="currentDish.allergen"></el-input>
            </el-form-item>
            <el-form-item label="主打菜品">
              <el-switch v-model="currentDish.isSignatureDish"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveDish">保存</el-button>
              <el-button @click="formVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import axios from '@/axios'
import { ElMessage } from 'element-plus';

export default {
  name: 'MenuManager',
  setup() {
    const store = useStore();
    const merchant_ID = computed(() => store.state.merchant.id);  // 从 Vuex store 中获取商家 ID

    const menuItems = ref([]);
    const formVisible = ref(false);
    const analysisVisible = ref(false); 
    const currentDish = ref({
      dish_ID: null,
      dish_name: '',
      dish_category: '',
      price: 0,
      description: '',
      ingredient: '',
      nutritionInfo: '',
      allergen: '',
      isSignatureDish: 0,
    });
    /* 获取商家菜单 */
    const fetchMenuItems = () => {
      axios.get(`/api/merchant/GetMenu/${merchant_ID.value}`)
        .then(response => {
          menuItems.value = response.data;
        })
        .catch(error => {
          ElMessage.error('无法获取菜单项');
        });
    };

    const addItem = () => {
      currentDish.value = {
        dish_ID: null,
        dish_name: '',
        dish_category: '',
        price: 0,
        description: '',
        ingredient: '',
        nutritionInfo: '',
        allergen: '',
        isSignatureDish: 0,
      };
      formVisible.value = true;  // 显示表单
    };

    const editDish = (dish) => {
      currentDish.value = { ...dish };
      formVisible.value = true;
    };

    const saveDish = () => {
      if(!currentDish.value.dish_name || !currentDish.value.price || currentDish.value.price <= 0 || !currentDish.value.dish_category) {
        ElMessage.error('请填写完整的菜品信息');
        return;
      }

      const dishData = {
        ...currentDish.value,
        isSignatureDish: currentDish.value.isSignatureDish ? 1 : 0, // 转换为 0 或 1
        merchant_ID: merchant_ID.value,
      };
      if (currentDish.value.dish_ID) { // 如果是编辑菜品
        axios.post(`/api/merchant/updateDish/${currentDish.value.dish_ID}`, dishData)
          .then(() => {
            ElMessage.success('菜品更新成功');
            fetchMenuItems();
            formVisible.value = false;
          })
          .catch(() => {
            ElMessage.error('菜品更新失败');
          });
      } else { // 如果是添加菜品
        axios.post(`/api/merchant/addDish`, dishData)
          .then(() => {
            ElMessage.success('菜品添加成功');
            fetchMenuItems();
            formVisible.value = false;
          })
          .catch(() => {
            ElMessage.error('菜品添加失败');
          });
      }
    };

    /* 商家删除菜品 */
    const deleteDish = (dish_ID) => {
      axios.post(`/api/merchant/deleteDish`, 
        { merchant_ID: merchant_ID.value,
          dish_ID: dish_ID})
        .then(() => {
          ElMessage.success('菜品删除成功');
          fetchMenuItems();
        })
        .catch(() => {
          ElMessage.error('菜品删除失败');
        });
    };
    const getMenu = () => {
      analysisVisible.value = false;
    };
    /* 获取菜品分析数据 */
    const getDishAnalysis = () => {
      analysisVisible.value = true;
    };

    const filterTag = (value, row) => {
      return row.isSignatureDish === (value === '是' ? 1 : 0);
    };

    onMounted(() => {
      fetchMenuItems();
    });

    return {
      menuItems,
      formVisible,
      analysisVisible,
      currentDish,
      addItem,
      editDish,
      saveDish,
      deleteDish,
      getDishAnalysis,
      getMenu,
      filterTag
    };
  }
};
</script>

<style scoped>
.narrow-form {
  width: 300px; /* 设置表单的宽度变窄 */
  /* margin: 20px auto; */
}

.dialog-footer {
  text-align: right;
}
</style>
